package com.java110.mall.cart.cmd.storeOrderCartReturn;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.storeOrder.StoreOrderDto;
import com.java110.dto.storeOrder.StoreOrderCartDto;
import com.java110.dto.storeOrder.StoreOrderCartEventDto;
import com.java110.dto.storeOrder.StoreOrderCartReturnDto;
import com.java110.dto.storeOrder.StoreOrderDiscountDto;
import com.java110.intf.cart.*;
import com.java110.po.storeOrder.StoreOrderPo;
import com.java110.po.storeOrder.StoreOrderCartPo;
import com.java110.po.storeOrder.StoreOrderCartEventPo;
import com.java110.po.storeOrder.StoreOrderCartReturnPo;
import com.java110.po.storeOrder.StoreOrderCartReturnEventPo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.math.BigDecimal;
import java.util.List;

/**
 * 退货申请
 */
@Java110Cmd(serviceCode = "/storeOrderCartReturn/applyReturnStoreCarts")
public class ApplyReturnStoreCartsCmd extends Cmd {

    @Autowired
    private IStoreOrderCartReturnInnerServiceSMO storeOrderCartReturnInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartReturnEventInnerServiceSMO storeOrderCartReturnEventInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartInnerServiceSMO storeOrderCartInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderInnerServiceSMO storeOrderInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartEventInnerServiceSMO storeOrderCartEventInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderDiscountInnerServiceSMO storeOrderDiscountInnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        Assert.hasKeyAndValue(reqJson, "shopId", "请求报文中未包含商铺");
        if (!reqJson.containsKey("orderCarts")) {
            Assert.hasKeyAndValue(reqJson, "orderId", "请求报文中未包含订单编号");

            StoreOrderCartDto storeOrderCartDto = new StoreOrderCartDto();
            storeOrderCartDto.setOrderId(reqJson.getString("orderId"));
            storeOrderCartDto.setStates(new String[]{StoreOrderCartDto.STATE_SENDING,
                    StoreOrderCartDto.STATE_WAIT_SEND,
                    StoreOrderCartDto.STATE_WAIT_REPAIR,
                    StoreOrderCartDto.STATE_FINISH,
                    StoreOrderCartDto.STATE_WAIT_SERV_DROP_IN,
                    StoreOrderCartDto.STATE_WAIT_SERV_WAIT_PAY,
                    StoreOrderCartDto.STATE_WAIT_SERV_R
            });
            List<StoreOrderCartDto> storeOrderCartDtos = storeOrderCartInnerServiceSMOImpl.queryStoreOrderCarts(storeOrderCartDto);
            Assert.listOnlyOne(storeOrderCartDtos, "当前不符合退货条件");

            reqJson.put("orderCarts", JSONArray.parseArray(JSONArray.toJSONString(storeOrderCartDtos)));
            reqJson.put("isOrder", true);
        }
    }

    @Override
    @Java110Transactional
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        JSONArray orderCarts = reqJson.getJSONArray("orderCarts");
        if (orderCarts == null || orderCarts.size() < 1) {
            throw new IllegalArgumentException("未包含 退货信息");
        }

        StoreOrderCartReturnPo storeOrderCartReturnPo = null;
        ResponseEntity<String> responseEntity = null;
        JSONObject paramOut = null;
        for (int orderCartIndex = 0; orderCartIndex < orderCarts.size(); orderCartIndex++) {
            storeOrderCartReturnPo = BeanConvertUtil.covertBean(orderCarts.getJSONObject(orderCartIndex), StoreOrderCartReturnPo.class);
            storeOrderCartReturnPo.setReturnReason(reqJson.getString("remark"));
            responseEntity = save(storeOrderCartReturnPo, reqJson);
            if (responseEntity.getStatusCode() != HttpStatus.OK) {
                throw new IllegalArgumentException(responseEntity.getBody());
            }

            paramOut = JSONObject.parseObject(responseEntity.getBody());
            if (paramOut.getIntValue("code") != ResultVo.CODE_OK) {
                throw new IllegalArgumentException(paramOut.getString("msg"));
            }
        }

        if (reqJson.containsKey("orderId")) {
            StoreOrderPo storeOrderPo = new StoreOrderPo();
            storeOrderPo.setOrderId(reqJson.getString("orderId"));
            storeOrderPo.setState(StoreOrderDto.STATE_APPLY_RETURN);
            int flag = storeOrderInnerServiceSMOImpl.updateStoreOrder(storeOrderPo);
            if (flag < 1) {
                throw new CmdException("退货失败");
            }
        }

        cmdDataFlowContext.setResponseEntity(responseEntity);
    }

    public ResponseEntity<String> save(StoreOrderCartReturnPo storeOrderCartReturnPo, JSONObject reqJson) {

        //查询
        StoreOrderCartDto storeOrderCartDto = new StoreOrderCartDto();
        storeOrderCartDto.setCartId(storeOrderCartReturnPo.getCartId());
        storeOrderCartDto.setStoreId(storeOrderCartReturnPo.getStoreId());
        storeOrderCartDto.setStates(new String[]{StoreOrderCartDto.STATE_SENDING,
                StoreOrderCartDto.STATE_WAIT_SEND,
                StoreOrderCartDto.STATE_FINISH,
                StoreOrderCartDto.STATE_WAIT_SERV_DROP_IN,
                StoreOrderCartDto.STATE_WAIT_SERV_WAIT_PAY,
                StoreOrderCartDto.STATE_WAIT_SERV_R
        });

        List<StoreOrderCartDto> storeOrderCartDtos = storeOrderCartInnerServiceSMOImpl.queryStoreOrderCarts(storeOrderCartDto);

        Assert.listOnlyOne(storeOrderCartDtos, "当前不符合退货条件");

        //判断 整单是否存在优惠
        String orderId = storeOrderCartDtos.get(0).getOrderId();
        StoreOrderDiscountDto storeOrderDiscountDto = new StoreOrderDiscountDto();
        storeOrderDiscountDto.setDiscountObjId(orderId);
        storeOrderDiscountDto.setDiscountObjType(StoreOrderDiscountDto.DISCOUNT_OBJ_TYPE_ORDER);
        List<StoreOrderDiscountDto> storeOrderDiscountDtos = storeOrderDiscountInnerServiceSMOImpl.queryStoreOrderDiscounts(storeOrderDiscountDto);
        if (storeOrderDiscountDtos != null && storeOrderDiscountDtos.size() > 0) {
            throw new IllegalArgumentException("订单存在优惠，请整单退单");
        }

        storeOrderCartReturnPo.setReturnId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_returnId));
        if (StringUtil.isEmpty(storeOrderCartReturnPo.getReturnCartNum())) {
            storeOrderCartReturnPo.setReturnCartNum(storeOrderCartDtos.get(0).getCartNum());
        }
        BigDecimal payPriceDec = new BigDecimal(storeOrderCartDtos.get(0).getPrice());
        storeOrderDiscountDto = new StoreOrderDiscountDto();
        storeOrderDiscountDto.setDiscountObjId(storeOrderCartReturnPo.getCartId());
        storeOrderDiscountDto.setDiscountObjType(StoreOrderDiscountDto.DISCOUNT_OBJ_TYPE_ORDER);
        storeOrderDiscountDtos = storeOrderDiscountInnerServiceSMOImpl.queryStoreOrderDiscounts(storeOrderDiscountDto);
        if (storeOrderDiscountDtos != null && storeOrderDiscountDtos.size() > 0) {
            if (!storeOrderCartReturnPo.getReturnCartNum().equals(storeOrderCartDtos.get(0).getCartNum())) {
                throw new IllegalArgumentException(storeOrderCartDtos.get(0).getProdName() + "存在 优惠，该商品需要全退");
            }
            payPriceDec = new BigDecimal(storeOrderCartDtos.get(0).getPayPrice());
        } else {
            payPriceDec = payPriceDec.multiply(new BigDecimal(storeOrderCartReturnPo.getReturnCartNum())).setScale(2, BigDecimal.ROUND_HALF_EVEN);
        }
        storeOrderCartReturnPo.setReturnPayPrice(payPriceDec.doubleValue() + "");
        storeOrderCartReturnPo.setReturnType(reqJson.containsKey("isOrder") ? StoreOrderCartReturnDto.RETURN_TYPE_ORDER : StoreOrderCartReturnDto.RETURN_TYPE_CART);
        storeOrderCartReturnPo.setState(StoreOrderCartReturnDto.STATE_APPLY);
        storeOrderCartReturnPo.setStoreId(storeOrderCartDtos.get(0).getStoreId());
        int flag = storeOrderCartReturnInnerServiceSMOImpl.saveStoreOrderCartReturn(storeOrderCartReturnPo);

        if (flag < 1) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
        }

        StoreOrderCartReturnEventPo storeOrderCartReturnEventPo = new StoreOrderCartReturnEventPo();
        storeOrderCartReturnEventPo.setEventId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId));
        storeOrderCartReturnEventPo.setEventMsg("用户申请退货");
        storeOrderCartReturnEventPo.setEventObjId(storeOrderCartReturnPo.getPersonId());
        storeOrderCartReturnEventPo.setEventObjType("U");//用户申请
        storeOrderCartReturnEventPo.setReturnId(storeOrderCartReturnPo.getReturnId());
        storeOrderCartReturnEventPo.setStoreId(storeOrderCartReturnPo.getStoreId());
        storeOrderCartReturnEventPo.setShopId(storeOrderCartReturnPo.getShopId());

        flag = storeOrderCartReturnEventInnerServiceSMOImpl.saveStoreOrderCartReturnEvent(storeOrderCartReturnEventPo);
        if (flag < 1) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
        }

        //加入订单事件
        StoreOrderCartEventPo storeOrderCartEventPo = new StoreOrderCartEventPo();
        storeOrderCartEventPo.setEventId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_eventId));
        storeOrderCartEventPo.setEventMsg("用户申请退货");
        storeOrderCartEventPo.setEventObjId(storeOrderCartReturnPo.getPersonId());
        storeOrderCartEventPo.setEventObjType("U");//用户申请
        storeOrderCartEventPo.setEventType(StoreOrderCartEventDto.EVENT_TYPE_COMMON);
        storeOrderCartEventPo.setOrderId(storeOrderCartDtos.get(0).getOrderId());
        storeOrderCartEventPo.setCartId(storeOrderCartDtos.get(0).getCartId());
        storeOrderCartEventPo.setShopId(storeOrderCartReturnPo.getShopId());

        flag = storeOrderCartEventInnerServiceSMOImpl.saveStoreOrderCartEvent(storeOrderCartEventPo);
        if (flag < 1) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
        }

        StoreOrderCartPo storeOrderCartPo = new StoreOrderCartPo();
        storeOrderCartPo.setCartId(storeOrderCartDtos.get(0).getCartId());
        storeOrderCartPo.setState(StoreOrderCartDto.STATE_REQ_RETURN);
        storeOrderCartPo.setStoreId(storeOrderCartDtos.get(0).getStoreId());
        storeOrderCartPo.setShopId(storeOrderCartReturnPo.getShopId());
        flag = storeOrderCartInnerServiceSMOImpl.updateStoreOrderCart(storeOrderCartPo);
        if (flag < 1) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
        }
        return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
    }
}
